﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Manipulations;
using System.Timers;
using System.Windows.Threading;

namespace MediaSurface
{
    


    public enum MediaState
    {
        NotStarted,
        Playing,
        Paused,
        Stopped,
        First
    }
    public partial class SurfaceUserControl1 : SurfaceUserControl
    {
         string urlsss;
         private LibraryBar mainLibBar; 
         static LibraryBar mainLbBar;
         
         string MovieTitle;
         int MediaPlayState = 0;
         double RemaingTime;
         int first_play = 0;

         public int movie_id;
         public string movie_title;
         public string length;
         public string tag;
         public string pool;
         
         static ScatterView scatterView2;
         static ScatterViewItem scatterItem;
         int removedValue1;
         string [] genere;
         BitmapImage bitmap = new BitmapImage(new Uri(@"C:\\Images\\control_pause.png"));
         BitmapImage bitmap1 = new BitmapImage(new Uri(@"C:\\Images\\control_play.png"));
           
       
         private DispatcherTimer _sliderTimer = new DispatcherTimer();
         private DispatcherTimer _controlsTimer = new DispatcherTimer();
         private DispatcherTimer _showRemainingMediaTime = new DispatcherTimer();


        

        public SurfaceUserControl1()
        {
            InitializeComponent();
        }


        public SurfaceUserControl1(ScatterView scatterV, ScatterViewItem sItem, LibraryBar lb, int removedVal, int id, string title, string length,  string pool, string aspect_ratio, string thumbnail_url, string description, string [] movieTags)
        {
            InitializeComponent();
            mainLbBar = lb;
            removedValue1 = removedVal;
            MovieTitle = title;
            genere = movieTags;
            scatterItem = sItem;
            scatterItem.ContactTapGesture += new ContactEventHandler(OnContactTapGesture1);
            ImageSourceConverter imgConv = new ImageSourceConverter();
            string path = thumbnail_url.ToString();
            if(path != "")
            {
                ImageSource imageSource = (ImageSource) imgConv.ConvertFromString(path);
                movie_thumnnail.Source = imageSource;
            }
            

            scatterView2 = scatterV;

            mainLbBar = lb;
            removedValue1 = removedVal;
            movie_id = id;
            movie_title = title;

            title_textBox.Text = title;
            length_textBox.Text = length;
            pool_textBox.Text = pool;
            description_textBox.Text = description;
            //if (genere[1] != null)
            try
            {
                tag_textBox.Text = genere[0] + " - " + genere[1]; 
                //else { tag_textBox.Text = genere[0]; }
            }
            catch { }
            
            if (aspect_ratio == "1")
            {
                aspect_Ratio_textBox.Text = "4x3";
                mediaInfo_StackPanel.Height = 310;
                movie_thumnnail.Height = 310;
            }
            if (aspect_ratio == "2")
            {
                aspect_Ratio_textBox.Text = "16x9";
            }
            
            
            State = MediaState.NotStarted;
            Title_Label.Content = "Title : " + MovieTitle;
           
            _sliderTimer.Interval = TimeSpan.FromMilliseconds(20);
            _sliderTimer.Tick += new EventHandler(_sliderTimer_Tick);

            Pause();
            McMediaElement.Visibility = System.Windows.Visibility.Collapsed;
            mediaInfo_StackPanel.Visibility = Visibility.Visible;
            thumbnail_stackPanel.Visibility = Visibility.Visible;
            
            _showRemainingMediaTime.Interval = TimeSpan.FromMilliseconds(35);
            _showRemainingMediaTime.Tick += new EventHandler(_showRemainingMediaTime_Tick);

           // Pause();

           // _controlsTimer.Interval = TimeSpan.FromSeconds(16);
            //_controlsTimer.Tick += new EventHandler(_controlsTimer_Tick); ;
            //_sliderTimer.Start();
           // _showRemainingMediaTime.Start();

            //Play();

        }


        




        public void SetMediaUrl(string url)
        {
            urlsss = url;
            McMediaElement.Source = new Uri(urlsss);
        }


        public MediaState State
        {
            get;
            set;
        }


        public virtual void Play()
        {

            mediaInfo_StackPanel.Visibility = Visibility.Collapsed;
            thumbnail_stackPanel.Visibility = Visibility.Collapsed;
            McMediaElement.Visibility = System.Windows.Visibility.Visible;
            McMediaElement.Play();
            _sliderTimer.Start();
            _showRemainingMediaTime.Start();
            this.State = MediaState.Playing;
            InitializePropertyValues();
            Play_Image.Source = bitmap;

           
        }


        public virtual void Play_1()
        {

            mediaInfo_StackPanel.Visibility = Visibility.Collapsed;
            thumbnail_stackPanel.Visibility = Visibility.Collapsed;

            McMediaElement.Visibility = System.Windows.Visibility.Visible;

            McMediaElement.Play();

            _sliderTimer.Start();
            _showRemainingMediaTime.Start();
            this.State = MediaState.First;
          
            InitializePropertyValues();

            Play_Image.Source = bitmap;

        }
        
        public virtual void Pause()
        {
            McMediaElement.Pause();
            _sliderTimer.Stop();
            _showRemainingMediaTime.Stop();
            this.State = MediaState.Paused;
            Play_Image.Source = bitmap1;
        }

        
        public virtual void Stop()
        {
            McMediaElement.Stop();
            _sliderTimer.Stop();
            _showRemainingMediaTime.Stop();
            this.State = MediaState.Stopped;
            Play_Image.Source = bitmap1;

        }



        public void setMediaBar(LibraryBar lb)
        {
            this.mainLibBar = lb;
        }

        void _sliderTimer_Tick(object sender, EventArgs e)
        {
            timelineSlider.Value = McMediaElement.Position.TotalSeconds;
        }


        void _showRemainingMediaTime_Tick(object sender, EventArgs e)
        {
            RemaingTime = (int)(McMediaElement.NaturalDuration.TimeSpan.TotalSeconds - McMediaElement.Position.TotalSeconds);

            Remaining_Time_Label.Content = "RemaingTime : " + RemaingTime.ToString() + " Seconds";
        }


        void _controlsTimer_Tick(object sender, EventArgs e)
        {
            if (!IsAnyContactOver)
            {
                mediaControls.Visibility = Visibility.Collapsed;
            }
        }

        private void Element_MediaEnded(object sender, RoutedEventArgs e)
        {
            this.State = MediaState.Stopped;
            McMediaElement.Stop();
            mediaControls.Visibility = Visibility.Visible;
            Play_Image.Source = bitmap1;
            McMediaElement.Position = TimeSpan.Zero;
            timelineSlider.Value = 0;

        }

       
        void OnContactDownPlayMedia(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {

            if (first_play == 0)
            {
                Play_1();
                first_play = 1;
            }


            else
            {
                if (MediaPlayState == 0)
                {
                    Play();

                    MediaPlayState = 1;

                }
                else
                {
                    Pause();

                    MediaPlayState = 0;
                }
            }

        }


        // Pause the media.
        void OnContactDownPauseMedia(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {

            Pause();

        }

        // Stop the media.
        void OnContactDownStopMedia(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {
            Stop();
         
        }


        protected override void OnContactEnter(ContactEventArgs e)
        {
            base.OnContactEnter(e);
            mediaControls.Visibility = Visibility.Visible;
            startTimer();
        }


        public void OnContactTapGesture1(object sender, ContactEventArgs e)
        {
            base.OnContactTapGesture(e);
            switch (this.State)
            {
                case MediaState.Stopped:
                    McMediaElement.Position = TimeSpan.Zero;
                    this.Play();
                    break;
                case MediaState.NotStarted:
                case MediaState.Paused:
                case MediaState.First:
                    this.Play();
                    break;
                case MediaState.Playing:
                    McMediaElement.Pause();
                    _sliderTimer.Stop();
                    _showRemainingMediaTime.Stop();
                    this.State = MediaState.Paused;
                    Play_Image.Source = bitmap1;
                    break;
            }

          //  if (mediaControls.Visibility != Visibility.Visible)
             //   mediaControls.Visibility = Visibility.Visible;
        }
        
        


        private void ChangeMediaVolume(object sender, RoutedPropertyChangedEventArgs<double> args)
        {
            McMediaElement.Volume = (double)volumeSlider.Value;
        }

      
        private void ChangeMediaSpeedRatio(object sender, RoutedPropertyChangedEventArgs<double> args)
        {
            //McMediaElement.SpeedRatio = (double)speedRatioSlider.Value;
        }

        
        private void Element_MediaOpened(object sender, EventArgs e)
        {
            timelineSlider.Maximum = McMediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            
        }

     
        

       
        private int valueChangedCount = 0;

        private void SeekToMediaPosition(object sender, RoutedPropertyChangedEventArgs<double> args)
        {
            if (timelineSlider.IsAnyContactOver && (++valueChangedCount > 3))
            {

                _sliderTimer.Stop();
                _showRemainingMediaTime.Stop();
                McMediaElement.Position = TimeSpan.FromSeconds(timelineSlider.Value);
                
                _sliderTimer.Start();
                _showRemainingMediaTime.Start();
                valueChangedCount = 0;



            }
            
        }

        private void slider_ContactChanged(object sender, ContactEventArgs e)
        {
            valueChangedCount = 0;
        }


        void InitializePropertyValues()
        {
            
            McMediaElement.Volume = (double)volumeSlider.Value;
         
            Title_Label.Content = "Title : " +MovieTitle;

            RemaingTime = McMediaElement.NaturalDuration.TimeSpan.TotalSeconds ;

            Remaining_Time_Label.Content =  "RemaingTime : " + RemaingTime.ToString();
        }


        private void startTimer()
        {
            //_controlsTimer.Start();
        }
        

        public void SurfaceButton_Click(object sender, RoutedEventArgs e )
        {

            
            
           McMediaElement.Stop();
           CloseSurfaceUserControl((SurfaceButton)sender);
           var item = mainLbBar.Items[removedValue1];

           mainLbBar.SetIsItemDataEnabled(item, true);

        }



        

        private void CloseSurfaceUserControl(SurfaceButton button)
        {
            DependencyObject parent = LogicalTreeHelper.GetParent(button);
            while (parent != null)
            {
                ScatterViewItem item = parent as ScatterViewItem;
                if (item != null)
                {
                    ScatterView scatterView = LogicalTreeHelper.GetParent(item) as ScatterView;
                    if (scatterView != null)
                    {
                        scatterView.Items.Remove(item);
                        return;
                    }
                }
                
                parent = LogicalTreeHelper.GetParent(parent);
            }
        }

      

        

       
    }
}
